// 功能点：
// 1. 音乐播放器页面
// 2. 音量条
// 3. 暂停按钮
// 4. 专辑旋转
// 5. 进度条
// 6. 计时器
// 7. 音乐评论、点赞
// 8. 歌词滚动及标亮
// 9. 搜索



// 1. 音乐播放器页面



// 默认url头部
const defaultHeader = 'http://127.0.0.1:3000';
// 搜索框
const displayAreaSearch = document.querySelector('.display-area-search');
// 搜索放大镜
const searchMagnifier = document.querySelector('.search-magnifier');
// 歌名
let currentSongName = document.querySelector('.current-song-name');
// 歌名补充（灰体）
let currentAlia = document.querySelector('.current-alia');
// 专辑图片
let currentAlbumPic = document.querySelector('.current-album-pic');
// 歌手
let currentPlayer = document.querySelector('.current-player');
// 专辑名
let currentAlbumName = document.querySelector('.current-album-name');
// 音频
let audio = document.querySelector('.audio');
// 音乐时长
let musicDuration = document.querySelector('.music-duration');
// 音乐进度
let musicProgressBox = document.querySelector('.music-progress');



// 解析url参数，拿到歌曲id
let str = location.search.split('?');
let songId = str[1].split('=')[1];
console.log('当前歌曲id为' + songId);



// 获取音乐详情
getMusicDetail(songId);



// 获取音乐详情
function getMusicDetail(songId) {
    ajaxRequest({
        url: `${defaultHeader}/song/detail`,

        data: {
            ids: songId
        },

        success: function (responseText) {
            console.log('获取音乐详情成功');
            console.log(responseText);

            // 渲染音乐基本信息
            MusicRender(responseText.songs[0]);
            // 获取音乐url
            getMusicUrl(songId);
            // 获取音乐评论
            getMusicComments(songId);
            // 获取音乐歌词
            getMusicLyrics(songId);
        },

        error: function (xhr) {
            console.log('获取音乐详情失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    });
}



// 渲染音乐基本信息
function MusicRender(song) {
    currentSongName.innerHTML = song.name;
    currentAlbumPic.style.backgroundImage = `url(${song.al.picUrl})`;
    currentPlayer.innerHTML = `歌手：${song.ar[0].name}`;
    currentAlbumName.innerHTML = `专辑：${song.al.name}`;
    musicDuration.innerHTML = getDuration(song.dt);

    // 判断是否有歌名补充
    if (song.alia.length !== 0) {
        currentSongName.className = 'current-song-alia-name';
        currentAlia.style.display = 'block';
        currentAlia.innerHTML = (song.alia.length) == 2 ? `${song.alia[0]} ${song.alia[1]}` : `${song.alia[0]}`;
    }
}



// 获取音乐url
function getMusicUrl(songId) {
    ajaxRequest({
        url: `${defaultHeader}/song/url`,

        data: {
            id: songId
        },
        success: function (responseText) {
            console.log('获取音乐url成功');
            console.log(responseText);

            // 把音频地址赋给audio
            audio.src = responseText.data[0].url;

            // 控制音量
            volumeControl();
        },

        error: function (xhr) {
            console.log('获取音乐url失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    });
}



// 2. 音量条



// 音量图标
let volumePic = document.querySelector('.volume-pic');
// 音量条盒子
let volumeBarBox = document.querySelector('.volume-bar-box');
// 音量条
let volumeBar = document.querySelector('.volume-bar');
// 音量值
let volumeValue = document.querySelector('.volume-value');



// 控制音量
function volumeControl() {
    volumeBarBox.onmousedown = function (e) {

        // 鼠标按下时，音量条显示
        let clickPosition = e.pageX - this.offsetLeft;
        volumeBar.style.width = clickPosition + 'px';

        // 音量即刻改变
        // volumeBarBox.offsetLeft = 100 代表音量条盒子长度
        audio.volume = clickPosition / 100;
        volumeValue.innerHTML = `${clickPosition}%`;

        // 鼠标按下时，添加鼠标移动事件
        document.onmousemove = function (e) {
            // 拖动时改变音量条长度
            // 这里注意不能用e.clientX，有误差
            let volumeBarLength = e.pageX - volumeBarBox.offsetLeft;

            // 拖动超出范围时，取边界值
            volumeBarLength = volumeBarLength > 100 ? 100 : volumeBarLength;
            volumeBarLength = volumeBarLength < 0 ? 0 : volumeBarLength;
            volumeBar.style.width = volumeBarLength + 'px';

            // 调整音量大小、显示音量值
            audio.volume = volumeBarLength / 100;
            volumeValue.innerHTML = `${volumeBarLength}%`;
        }

        // 鼠标松开时，删除以上两个事件
        document.onmouseup = () => {
            document.onmousedown = null;
            document.onmousemove = null;
        }
    }

    // 控制静音的变量
    let isMuted = false;
    // 保存静音前的音量
    let currentVolume;
    // 保存静音前的音量条长度
    let currentBarLength;

    // 点击音量图标，静音播放
    volumePic.addEventListener('click', () => {
        if (!isMuted) {
            // 记录静音前的音量、音量条长度
            currentVolume = audio.volume;
            currentBarLength = volumeBar.offsetWidth;

            // 静音后，音量值、音量条都会改变
            volumeValue.innerHTML = '0%';
            volumeBar.style.width = '0';
            audio.volume = 0;

            isMuted = true;
        } else {
            // 恢复静音前的音量、音量条长度、音量大小
            audio.volume = currentVolume;
            volumeBar.style.width = currentBarLength + 'px';
            volumeValue.innerHTML = `${currentBarLength}%`;

            isMuted = false;
        }
    })
}



// 3. 暂停按钮



// 播放暂停按钮盒子
let playPauseBtn = document.querySelector('.play-pause');
// 播放暂停按钮样式
let playOrPause = document.querySelector('.play-pause-btn');



// 播放暂停按钮点击事件
playPauseBtn.addEventListener('click', () => {
    // audio.paused判断播放状态
    if (audio.paused) {
        playOrPause.className = 'play playOrPause';
        audio.play();

        // 专辑图旋转
        albumRotate();
    } else {
        playOrPause.className = 'pause playOrPause';
        audio.pause();

        // 专辑图停止旋转
        stopAlbumRatate();
    }
})



// 歌曲播放结束时，专辑图、按钮恢复原状
audio.addEventListener('ended', () => {
    // 专辑图停止旋转
    stopAlbumRatate();
    playOrPause.className = 'pause playOrPause';
})



// 4. 专辑旋转



// 专辑图旋转的定时器
let rotateTimer;
// 专辑图旋转角度
let rotateAngle = 0;



// 专辑图旋转
function albumRotate() {
    // 定时器
    rotateTimer = setInterval(() => {
        rotateAngle += 1;
        currentAlbumPic.style.transform = `rotate(${rotateAngle}deg)`;
        currentAlbumPic.style.transition = '0.1s linear';

        // 歌曲播放结束时旋转角度复原
        audio.addEventListener('ended', () => {
            currentAlbumPic.style.transform = 'rotate(0deg)';
            rotateAngle = 0;
        })
    }, 100)
}



// 专辑图停止旋转
function stopAlbumRatate() {
    clearInterval(rotateTimer);
}



// 5. 进度条



// 进度条盒子
let progressBarBox = document.querySelector('.progress-bar-box');
// 进度条
let progressBar = document.querySelector('.progress-bar');



// 歌曲播放时进度条加载
audio.addEventListener('timeupdate', () => {

    // 高频计算 当前播放时长/总时长
    let progressRatio = audio.currentTime / audio.duration;
    progressBar.style.width = progressRatio * 400 + 'px';

    // 拖拽进度条，实时改变歌曲进度，思路大致同音量控制
    progressBarBox.onmousedown = function (e) {

        // 鼠标按下时，进度条更新
        let clickPosition = e.pageX - progressBarBox.offsetLeft;
        progressBar.style.width = clickPosition + 'px';
        // 歌曲进度也即刻改变
        audio.currentTime = clickPosition / 400 * parseInt(audio.duration);

        // 鼠标按下时添加鼠标移动事件
        document.onmousemove = function (e) {
            // 移动时反复改变进度条长度
            let progressBarLength = e.pageX - progressBarBox.offsetLeft;

            // 拖动超出范围，取边界值
            progressBarLength = progressBarLength > 400 ? 400 : progressBarLength;
            progressBarLength = progressBarLength < 0 ? 0 : progressBarLength;
            progressBar.style.width = progressBarLength + 'px';

            // 调整歌曲进度
            audio.currentTime = progressBarLength / 400 * parseInt(audio.duration);
        }

        // 鼠标松开时，删除以上两个事件
        // document.onmouseup可实现鼠标在进度条盒子外面松开后，不再触动进度条事件
        // 用progressBarBox.onmouseup的话，鼠标滑出进度条后松开，再回到进度条上还会触发进度条事件
        document.onmouseup = () => {
            document.onmousedown = null;
            document.onmousemove = null;
        }
    }

    // 歌曲播放结束时，进度条长度重置
    audio.addEventListener('ended', () => {
        progressBar.style.width = 0;
    })
})



// 6. 计时器



let minute = 0,
    second = 0;



// 歌曲播放时，计时器加载
audio.addEventListener('timeupdate', () => {
    minute = parseInt(parseInt(audio.currentTime) / 60);
    second = parseInt(audio.currentTime) - 60 * minute;

    minute = minute >= 10 ? minute : '0' + minute;
    second = second >= 10 ? second : '0' + second;

    musicProgressBox.innerHTML = `${minute}:${second}/`;
})



// 歌曲结束时，恢复计时
audio.addEventListener('ended', () => {
    musicProgressBox.innerHTML = '00:00/';
})



// 7. 音乐评论、点赞



// 获取音乐评论
function getMusicComments(songId) {
    ajaxRequest({
        url: `${defaultHeader}/comment/music`,

        data: {
            id: songId
        },

        success: function (responseText) {
            console.log('获取音乐评论成功');
            console.log(responseText);

            // 渲染三条评论
            renderComments(responseText.hotComments, responseText.comments, songId);
        },

        error: function (xhr) {
            console.log('获取音乐评论失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    });
}



// 评论item
let commentsItems = document.querySelectorAll('.comments-item');
// 滚动盒子
let commentScroll = document.querySelector('.comment-scroll');
// 滚动区
let scrollArea = document.querySelector('.scroll');
// 评论用户头像
let commentsUsersHead = document.querySelectorAll('.comments-head');
// 评论用户名字
let commentsUsersName = document.querySelectorAll('.comments-name');
// 评论时间
let commentsTimes = document.querySelectorAll('.comments-time');
// 评论内容
let commentsContent = document.querySelectorAll('.comments-content');
// 点赞数
let currentLike = document.querySelectorAll('.comments-like');
// 点赞按钮
let giveLikeBtn = document.querySelectorAll('.commments-give-like');



// 渲染三条评论
function renderComments(hotComments, comments, songId) {
    if (hotComments.length) {

        let count = hotComments.length >= 3 ? 3 : hotComments.length;

        if (count == 3) {
            // 渲染每条item
            eachCommentItem(count, hotComments, songId);
        } else if (count == 2) {
            // 渲染每条item
            eachCommentItem(count, hotComments, songId);

            commentsItems[2].style.display = 'none';
            scrollArea.style.height = 120 * count;
        } else {
            // 渲染每条item
            eachCommentItem(count, hotComments, songId);

            // 隐藏下面两个评论盒子
            commentsItems[1].style.display = 'none';
            commentsItems[2].style.display = 'none';
            scrollArea.style.height = 120 * count;
        }
    } else if (comments.length) {

        let count = comments.length >= 3 ? 3 : comments.length;

        if (count == 3) {
            // 渲染每条item
            eachCommentItem(count, comments, songId);
        } else if (count == 2) {
            // 渲染每条item
            eachCommentItem(count, comments, songId);

            commentsItems[2].style.display = 'none';
            scrollArea.style.height = 120 * count;
        } else {
            // 渲染每条item
            eachCommentItem(count, comments, songId);

            // 隐藏下面两个评论盒子
            commentsItems[1].style.display = 'none';
            commentsItems[2].style.display = 'none';
            scrollArea.style.height = 120 * count;
        }
    } else {
        scrollArea.style.display = 'none';
        commentScroll.innerHTML = '当前歌曲暂无评论';
    }
}



// 渲染每条item
function eachCommentItem(count, obj, songId) {
    for (let i = 0; i < count; i++) {

        commentsUsersHead[i].style.backgroundImage = `url(${obj[i].user.avatarUrl})`;
        commentsUsersName[i].innerHTML = obj[i].user.nickname;
        commentsTimes[i].innerHTML = obj[i].timeStr;
        commentsContent[i].innerHTML = obj[i].content;
        currentLike[i].innerHTML = `${obj[i].likedCount}人觉得很赞`;

        // 判断是否点赞的变量
        let flag = true;

        // "点赞"功能
        giveLikeBtn[i].addEventListener('click', () => {

            if (flag) {
                ajaxRequest({
                    url: `${defaultHeader}/comment/like`,

                    data: {
                        id: songId,
                        cid: obj[i].commentId,
                        t: 1,
                        type: 0
                    },

                    success: function (responseText) {
                        console.log('点赞成功');
                        console.log(responseText);

                        giveLikeBtn[i].innerHTML = '已赞';
                        giveLikeBtn[i].style.backgroundColor = 'coral';
                    },

                    error: function (xhr) {
                        console.log('点赞失败');
                        console.log(xhr.readyState);
                        console.log(xhr.status);
                    }
                })

                flag = false;

            } else {
                ajaxRequest({
                    url: `${defaultHeader}/comment/like`,

                    data: {
                        id: songId,
                        cid: obj[i].commentId,
                        t: 0,
                        type: 0
                    },

                    success: function (responseText) {
                        console.log('取消点赞成功');
                        console.log(responseText);

                        giveLikeBtn[i].innerHTML = '点赞';
                        giveLikeBtn[i].style.backgroundColor = '#31C27C';
                    },

                    error: function (xhr) {
                        console.log('取消点赞失败');
                        console.log(xhr.readyState);
                        console.log(xhr.status);
                    }
                })

                flag = true;

            }
        })
    }
}



// 8. 歌词滚动及标亮



// 获取音乐歌词
function getMusicLyrics(songId) {
    ajaxRequest({
        url: `${defaultHeader}/lyric`,

        data: {
            id: songId
        },

        success: function (responseText) {
            console.log('获取音乐歌词成功');
            console.log(responseText);

            // 处理音乐歌词
            analyzeMusicLyrics(responseText.lrc.lyric);
        },

        error: function (xhr) {
            console.log('获取音乐歌词失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    })
}



// 处理音乐歌词
function analyzeMusicLyrics(lyric) {

    let lrc = lyric.split('['),
        eachTime = [],
        eachLyric = [],
        lrcLength = lrc.length;

    // 分离时间和数组
    for (let i = 0; i < lrcLength; i++) {
        let elementItem = lrc[i].split(']');
        eachTime[i] = elementItem[0];
        eachLyric[i] = elementItem[1];
    }

    // 截掉第一个空元素
    eachTime.shift();
    eachLyric.shift();

    let eachLyricLength = eachLyric.length;

    // 去除空行，先从歌词数组里删，再删除时间数组里对应的元素
    for (let i = 0; i < eachLyricLength; i++) {
        if (eachLyric[i] === '\n') {
            eachLyric.splice(i, 1);
            eachTime.splice(i, 1);
        }
    }

    // 渲染歌词
    renderLyrics(eachTime, eachLyric);
}



// 歌词滚动区
let lyricBox = document.querySelector('.song-words-scroll');



// 渲染歌词
function renderLyrics(time, lyric) {

    let timeLength = time.length,
        lyricLength = lyric.length;

    // 创建歌词行节点
    for (let i = 0; i < lyricLength; i++) {
        let lineLyric = document.createElement('div');
        lyricBox.appendChild(lineLyric);
        lineLyric.className = 'line-lyric';
        lineLyric.setAttribute('data-number', i);
        lineLyric.innerHTML = lyric[i];
    }

    // 歌词行
    let eachLineLyric = document.querySelectorAll('.line-lyric');

    // 存放歌词时间
    let lyricArr = [];

    for (let i = 0; i < timeLength; i++) {
        lyricArr[i] = getMilisecond(time[i]);
    }

    console.log(lyricArr);

    // 控制索引的变量
    let cunt = 0,
        lyricArrLength = lyricArr.length;

    // 音乐进度更新时匹配时间
    audio.addEventListener('timeupdate', function () {

        // 把音乐进度转化为毫秒
        let audioTime = parseInt(this.currentTime * 1000);

        // 针对拖动进度条、点击歌词时，定位到对应歌词行
        for (let i = 0; i < lyricArrLength; i++) {
            if (audioTime - lyricArr[i] <= 300 && audioTime - lyricArr[i] > 0) {
                cunt = i;
            }
        }

        // 和当前歌词的时间差进入范围时
        if (audioTime - lyricArr[cunt] <= 300 && audioTime - lyricArr[cunt] > 0) {

            for (let i = 0; i < lyricArrLength; i++) {
                eachLineLyric[i].className = 'line-lyric';
            }

            // 字体样式改变
            eachLineLyric[cunt].className = 'current-lyric';

            // 滚动效果
            lyricBox.style.top = 360 - (cunt + 1) * 60 + 'px';
            cunt++;
        }
    })

    // 点击歌词 实现进度更新
    for (let i = 0; i < lyricLength; i++) {
        eachLineLyric[i].addEventListener('click', () => {
            audio.currentTime = parseInt(lyricArr[i] / 1000);
            cunt = i;
        })
    }

    // 音乐结束时，恢复原状态
    audio.addEventListener('ended', function () {
        lyricBox.style.top = '360px';

        for (let i = 0; i < lyricLength; i++) {
            eachLineLyric[i].className = 'line-lyric';
        }

        cunt = 0;
    })
}



// 9. 搜索



// 搜索结果盒子
let searchResultBox = document.querySelector('.search-result-box');



// 搜索
searchMagnifier.addEventListener('click', () => {
    let searchText = displayAreaSearch.value;
    if (searchText !== '') {
        ajaxRequest({
            url: `${defaultHeader}/cloudsearch`,

            data: {
                keywords: searchText,
                type: 1
            },

            success: function (responseText) {
                console.log('搜索成功');
                console.log(responseText);

                if (responseText.result.songCount !== 0) {
                    // 渲染搜索结果
                    searchResult(responseText.result.songs);
                }
            },

            error: function (xhr) {
                console.log('搜索失败');
                console.log(xhr.readyState);
                console.log(xhr.status);
            }
        })
    } else {
        displayAreaSearch.placeholder = '搜索内容不能为空';

        displayAreaSearch.addEventListener('focus', function () {
            this.placeholder = '搜索音乐(建议精确搜索)';
        })
    }
})



// 渲染搜索结果
function searchResult(songs) {

    searchResultBox.style.display = 'block';

    let songsLength = songs.length >= 5 ? 5 : songs.length;

    for (let i = 0; i < songsLength; i++) {
        // 创建节点
        let songLi = document.createElement('li');
        searchResultBox.appendChild(songLi);
        songLi.className = 'search-result-item';
        songLi.innerHTML = `${songs[i].name} - ${songs[i].ar[0].name} - ${songs[i].al.name}`;

        // 点击item，读取id，重新加载页面
        songLi.addEventListener('click', () => {
            location.assign(`music.html?id=${songs[i].id}`);
        })

        searchMagnifier.addEventListener('click', () => {
            for (let i = 0; i < songsLength; i++) {
                songLi.parentNode.removeChild(songLi);
            }
        })
    }

    displayAreaSearch.addEventListener('blur', () => {
        searchResultBox.style.display = 'none';
    })

    displayAreaSearch.addEventListener('input', () => {
        searchResultBox.style.display = 'none';
    })
}







// let playRecordLi = document.createElement('li');
// playRecordUl.appendChild(playRecordLi);
// playRecordLi.className = 'play-record-li';
// playRecordLi.innerHTML = currentSongName.innerHTML;